import logging
from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework import status
from redis import RedisError

logger = logging.getLogger('django')
def custom_exception_handler(exc,context):
    #框架能捕捉到的异常
    response = exception_handler(exc, context)

    if response is None:
        #为空  1.程序无异常   2.数据库异常
        if isinstance(exc,DatabaseError) or isinstance(exc,RedisError):
            #数据库异常,写入日志
            logger.error(f'{context['view']: {exc} }')
            return Response({'error': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
        
    return response
